from django.db import transaction
from rest_framework import serializers
from goods.models import GoodsChannel, GoodsCategory, GoodsChannelGroup


class GoodsChannelSerializer(serializers.ModelSerializer):
    group = serializers.StringRelatedField()
    category = serializers.StringRelatedField()
    channels = serializers.StringRelatedField()
    category_id = serializers.IntegerField()
    group_id = serializers.IntegerField()
    class Meta:
        model=GoodsChannel
        fields = ('__all__')

    def create(self, validated_data):
        def create(self, validated_data):
            with transaction.atomic():
                save_point = transaction.savepoint()
                try:
                    specs = validated_data['specs']
                    del validated_data['specs']
                    sku = GoodsChannel.objects.create(**validated_data)
                    for spec in specs:
                        GoodsChannelGroup.objects.create(sku=sku, spec_id=spec['spec_id'], option_id=spec['option_id'])
                except:
                    transaction.savepoint_rollback(save_point)
                    raise serializers.ValidationError('保存数据失败')
                else:
                    transaction.savepoint_commit(save_point)

class GoodsChannelGroupSerializer(serializers.ModelSerializer):
    name = serializers.StringRelatedField()
    class Meta:
        model = GoodsChannelGroup
        fields = ('__all__')

class categoriesSerializers(serializers.ModelSerializer):
    category1_id = serializers.IntegerField()

    class Meta:
        model  = GoodsCategory
        fields = ('__all__')